<template>
    <div :style="carStyle">
        <div v-if="!showContent" class="defaultText">请在右侧配置数据</div>
        <template v-else>
            <div class="lineTitle" v-if="obj.isShowTitle" :style="titleStyle">{{ obj.title }}</div>
        </template>
        <div class="chart" ref="constat" :style="canvasStyle"></div>
    </div>
</template>

<script>
import * as echarts from 'echarts';
import moment from "moment"
// import { cardDataLoad, boardLoad } from '@/api/share'
var defaultData = [
    [
        '系列3',
        1684203943710,
        1684203948314,
        1684203950588,
        1684203960431,
        1684203963161,
        1684203976960,
        1684203979994,
        1684203988473,
        1684203991103,
        1684203996042,
        1684204001586,
        1684204006808,
    ],
    [
        '系列2',
        1684203943710,
        1684203946550,
        1684203949230,
        1684203951298,
        1684203952048,
        1684203960340,
        1684203963776,
        1684203973768,
        1684203977930,
        1684203985505,
        1684203993806,
        1684203998105,
    ],
    [
        '系列1',
        1684203941710,
        1684203950055,
        1684203952152,
        1684203958859,
        1684203960359,
        1684203961446,
        1684203962253,
        1684203966052,
        1684203970005,
        1684203979884,
        1684203982798,
        1684203994163,
    ]
];
var defaultItem = [
    { name: 'JS Heap', color: '#7b9ce1' },
    { name: 'Documents', color: '#bd6d6c' },
    { name: 'Nodes', color: '#75d874' },
    { name: 'Listeners', color: '#e0bc78' },
    { name: 'GPU Memory', color: '#dc77dc' },
    { name: 'GPU', color: '#72b362' }
];

export default {
    Name: "Gantetu",
    components: {
        echarts
    },
    props: {
        obj: Object,
        isReload: {
            type: Boolean,
            default: false
        },
        isEdit: {
            type: Boolean,
            default: false,
        },
    },
    data() {
        return {
            showContent: false,
            carStyle: {},
            titleStyle: {},
            canvasStyle: {
                width: "100%",
                height: "100%"
            },
            chart: undefined,
            // 用于比对数据是否修改
            dataStr: "",
            filterForm: {
                pageInfo: {
                    pageSize: 1,
                    page: 1,
                    totalCount: 0
                },
                tableId: 0,
                structureIds: [],
                beginTime: undefined,
                endTime: undefined,
                sortType: "1",
                dateTime: "",
            },
            timer: null,
        }
    },
    mounted() {
        this.setStyle();

        this.$nextTick(function () {
            this.reloadInfo();
        })

        this.dataStr = JSON.stringify(this.obj.tableData);

        // 页面变化调整尺寸
        var self = this;
        window.addEventListener('resize', function () {
            if (self.chart) {
                self.chart.resize();
            }
        }, true);
    },
    beforeDestroy() {
        if (!this.chart) {
            return
        }
        this.chart.dispose()
        this.chart = null
        clearInterval(this.timer)
    },
    methods: {
        reloadInfo() {
            var self = this;

            // 重绘
            if (this.chart) {
                this.chart.dispose()
            }
            var constat = this.$refs.constat;
            this.chart = echarts.init(constat);

            var timeSize = 60;
            if (this.obj.tableData.reloadTime) {
                timeSize = this.obj.tableData.reloadTime;
            }

            // #region
            const end = new Date();
            const start = new Date();
            if (this.obj.tableData.type == 0) {
                this.filterForm.isOnlie = true;

                // 查询一天内数据
                start.setTime(start.getTime() - 3600 * 1000 * 24);
                this.filterForm.beginTime = this.parseTime(start);
                this.filterForm.endTime = this.parseTime(end);
            } else {
                this.filterForm.isOnlie = false;

                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                this.filterForm.beginTime = this.parseTime(start, "{y}-{m}-{d}");
                this.filterForm.endTime = this.parseTime(end);

                // 刷新时间兼容处理
                if (timeSize < 60) {
                    timeSize = 60;
                }
            }
            // #endregion

            clearInterval(this.timer);

            this.getLineData((dataResult) => {
                var data = self.resultDataToObject(self.obj.tableData.barList, dataResult.dataList);
                self.setOptions(data.axisItem, data.seriesData);
            });

            if (this.isReload) {
                this.timer = setInterval(() => {
                    const end = new Date();
                    this.filterForm.endTime = this.parseTime(end);

                    this.getLineData((dataResult) => {
                        var data = self.resultDataToObject(self.obj.tableData.barList, dataResult.dataList);
                        self.setOptions(data.axisItem, data.seriesData);
                    });
                }, timeSize * 1000);
            }
        },
        // 数据转换
        resultDataToObject(columns, dataList) {
            var newColors = ['#fc8251', '#5470c6', '#91cd77', '#ef6567', '#f9c956', '#75bedc'];
            if (this.obj.tableData.colors) {
                newColors = this.obj.tableData.colors;
            }
            console.log(dataList);
            var axisItem = [];
            var seriesData = [];
            if (dataList.length) {
                dataList.forEach((lineData, index) => {
                    axisItem.push(lineData[0])
                    var data = [];
                    for (var i = 0; i < columns.length; i++) {
                        var v1 = lineData[i * 2 + 1];
                        if (typeof v1 == "string") {
                            v1 = Date.parse(v1);
                        }
                        var v2 = lineData[i * 2 + 2];
                        if (typeof v2 == "string") {
                            v2 = Date.parse(v2);
                        }
                        data.push({
                            name: columns[i].name,
                            value: [
                                index,
                                v1,
                                v2,
                                v2 - v1
                            ],
                            itemStyle: {
                                normal: {
                                    color: newColors[i]
                                }
                            }
                        });

                    }
                    seriesData = seriesData.concat(data)
                });
            }

            return {
                axisItem,
                seriesData
            }
        },
        setStyle() {
            var style = this.obj.style;

            // #region 组件背景图或颜色
            var backgroundColor = "";
            var backgroundImage = "";

            if (style.backgroundImage.length) {
                backgroundImage = `url(${style.backgroundImage}`;
            } else if (style.backgroundColor.length > 0) {
                backgroundColor = style.backgroundColor;
            } else {
                backgroundColor = "";
            }
            // #endregion

            // #region 组件投影
            var boxShadow = "";
            if (style.boxShadow) {
                boxShadow = `${style.boxShadow.h}px ${style.boxShadow.v}px ${style.boxShadow.blur}px ${style.boxShadow.spreed}px ${style.boxShadow.color}`
            }
            // #endregion

            this.carStyle = {
                boxShadow,
                width: "100%",
                height: "100%",
                display: "flex",
                backgroundSize: "100% 100%",
                borderStyle: "solid",
                // backgroundImage,
                // backgroundColor,
                color: style.color,
                fontSize: style.fontSize + "px",
                justifyContent: style.justifyContent,
                alignItems: style.alignItems,
                borderColor: style.borderColor,
                borderWidth: style.borderWidth + "px",
                borderRadius: style.borderRadius + "px",
                fontWeight: style.fontWeight,
                fontStyle: style.fontStyle,
            }

            // #region 新的背景颜色

            if (this.obj.style.bgcolorType == "image") {
                this.carStyle.backgroundImage = backgroundImage;
            } else if (this.obj.style.bgcolorType == "gradient") {
                if (this.obj.style.gradient.isRadial) {
                    this.carStyle.backgroundImage = `radial-gradient(${this.obj.style.gradient.colorStart}, ${this.obj.style.gradient.colorEnd})`;
                } else {
                    this.carStyle.backgroundImage = `linear-gradient(${this.obj.style.gradient.fontAngle}deg, ${this.obj.style.gradient.colorStart}, ${this.obj.style.gradient.colorEnd})`;
                }
            } else {
                this.carStyle.backgroundColor = backgroundColor;
            }

            // #endregion

            this.titleStyle = {
                justifyContent: style.justifyContent,
                alignItems: style.alignItems,
            }

            // 标题隐藏显示
            var isShowTitle = this.obj.isShowTitle ? true : false;
            var echarHeight = style.height;
            var echarMarginTop = 0;
            if (isShowTitle) {
                echarHeight = style.height - style.fontSize - style.borderWidth * 2;
                echarMarginTop = style.fontSize + "px";
            }

            this.canvasStyle = {
                marginTop: echarMarginTop,
                width: "100%",
                height: echarHeight + "px",
            }

            if (this.chart) {
                this.chart.resize({
                    width: style.width,
                    height: echarHeight,
                });
            }
        },
        setOptions(axisItem, seriesData) {
            var self = this;

            // #region 系列颜色
            var color = "#333333";
            if (this.obj.tableData.color) {
                color = this.obj.tableData.color;
            }

            var lineColor = "#eeeeee"
            if (this.obj.tableData.lineColor) {
                lineColor = this.obj.tableData.lineColor;
            }
            // #endregion

            // #region 图例 legend样式
            var isShowLegend = true;
            if (this.obj.tableData.isShowLegend != undefined) {
                isShowLegend = this.obj.tableData.isShowLegend;
            }
            var icon = "circle";
            if (this.obj.tableData.icon) {
                icon = this.obj.tableData.icon;
            }

            var textColor = "#333333";
            if (this.obj.tableData.textColor) {
                textColor = this.obj.tableData.textColor;
            }
            var textFontsize = '14px';
            if (this.obj.tableData.textfontSize) {
                textFontsize = this.obj.tableData.textfontSize + "px";
            }
            var textFontWeight = "";
            if (this.obj.tableData.textFontWeight) {
                textFontWeight = this.obj.tableData.textFontWeight;
            }
            var textFontStyle = "";
            if (this.obj.tableData.textFontStyle) {
                textFontStyle = this.obj.tableData.textFontStyle;
            }

            // #endregion

            this.chart.setOption({
                grid: {
                    left: "2%",
                    right: "6%",
                    top: "60px",
                    bottom: "10px",
                    containLabel: true
                },
                // legend: {
                //     type: 'scroll',
                //     data: ['故障', '换模', '换刀'],
                //     show: true,
                //     orient: 'vertical',
                //     align: 'auto',
                //     top: '10%',
                //     right: '2%',
                //     // top: "25px",
                //     // left: "15px",
                //     // show: isShowLegend,
                //     // // orient: orient,
                //     // right: 10,
                //     // textStyle: {
                //     //     color: textColor,
                //     //     fontSize: textFontsize,
                //     //     fontWeight: textFontWeight,
                //     //     fontStyle: textFontStyle,
                //     // },
                //     // icon,
                //     // formatter: (val) => {
                //     //     return val;
                //     // }
                // },
                tooltip: {
                    formatter: function (params) {
                        return params.marker + params.name + ': ' + params.value[3] + ' ms';
                    }
                },
                // dataZoom: [{
                //     type: 'inside',
                //     filterMode: 'weakFilter'
                // }],
                xAxis: {
                    scale: true,
                    splitLine: {
                        show: this.obj.tableData.isShowGrid,
                        lineStyle: {
                            color: lineColor,
                            width: 1,
                        }
                    },
                    axisLabel: {
                        color: color,
                        formatter: function (val) {
                            return moment(val).format("YYYY/MM/DD") + "\n" + moment(val).format("HH:mm:ss")
                        }
                    }
                },
                yAxis: {
                    data: axisItem,
                    axisLabel: {
                        color: color,
                    },
                    splitLine: {
                        show: this.obj.tableData.isShowGrid,
                        lineStyle: {
                            color: lineColor,
                            width: 1,
                        }
                    },
                },
                series: [{
                    type: 'custom',
                    renderItem: function (params, api) {
                        var categoryIndex = api.value(0);
                        var start = api.coord([api.value(1), categoryIndex]);
                        var end = api.coord([api.value(2), categoryIndex]);
                        var height = api.size([0, 1])[1] * 0.6;

                        var rectShape = echarts.graphic.clipRectByRect({
                            x: start[0],
                            y: start[1] - height / 2,
                            width: end[0] - start[0],
                            height: height
                        }, {
                            x: params.coordSys.x,
                            y: params.coordSys.y,
                            width: params.coordSys.width,
                            height: params.coordSys.height
                        });

                        return rectShape && {
                            type: 'rect',
                            shape: rectShape,
                            style: api.style()
                        };
                    },
                    itemStyle: {
                        normal: {
                            opacity: 0.8
                        }
                    },
                    encode: {
                        x: [1, 2],
                        y: 0
                    },
                    data: seriesData
                }]
            });
        },
        getLineData(callback) {

            // #region 没有配置数据显示默认内容
            if (!this.obj.tableData.tableId) {
                this.showContent = true;
                var data = this.resultDataToObject(defaultItem, defaultData);
                this.setOptions(data.axisItem, data.seriesData);
                return false;
            }
            // #endregion

            // #region 参数不完整
            var idlist = [this.obj.tableData.xId];
            if (this.obj.tableData.barList.length == 0) {
                this.showContent = false;
                return false;
            }
            this.obj.tableData.barList.forEach(e => {
                if (e.beginTimeId) {
                    idlist.push(e.beginTimeId);
                }
                if (e.endTimeId) {
                    idlist.push(e.endTimeId);
                }
            });
            if (idlist.length - 1 != this.obj.tableData.barList.length * 2) {
                this.showContent = false;
                return false;
            }
            // #endregion

            this.showContent = true;
            this.filterForm.tableId = this.obj.tableData.tableId;
            this.filterForm.pageInfo.pageSize = this.obj.tableData.count;
            this.filterForm.structureIds = idlist;

            if (this.obj.tableData.type != 1) {
                cardDataLoad(this.filterForm).then((res) => {
                    if (res.data.code == 0) {
                        if (callback) {
                            callback(res.data.data.dataResult);
                        }
                    } else {
                        console.error(res.data.message)
                    }
                }).catch(() => {
                    clearInterval(this.timer)
                });
            } else {
                boardLoad(this.filterForm).then((res) => {
                    if (res.data.code == 0) {
                        if (callback) {
                            callback(res.data.data.dataResult);
                        }
                    } else {
                        console.error(res.data.message)
                    }
                }).catch(() => {
                    clearInterval(this.timer)
                });
            }
        }
    },
    watch: {
        obj: {
            handler(newVal, oldVal) {
                this.setStyle();

                // 数据改变了 动态更新echart
                if (JSON.stringify(this.obj.tableData) != this.dataStr) {
                    this.dataStr = JSON.stringify(this.obj.tableData);

                    this.reloadInfo();
                }
            },
            deep: true,  // 深度监听
        }
    },
}
</script>